package com.shortchainsystem.link.controller;

import com.shortchainsystem.link.service.LinkService;
import com.shortchainsystem.model.base.Result;
import com.shortchainsystem.model.domain.link.DTO.StaticDTO;
import com.shortchainsystem.util.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/static")
@Slf4j
public class StaticController {
    @Autowired
    private LinkService linkService;

    /**
     *   根据时间范围类型获取概览数据（生成量、访问量、访问用户数、访问IP数）
     */
    @PostMapping("/historyShow")
    public Result historyShow(@RequestBody StaticDTO staticDTO, HttpServletRequest request){
        String userId = getUserId(request);
        return linkService.historyShow(staticDTO,userId);
    }

    /**
     *   获取最佳访问记录
     */
    @PostMapping("/accessHistory")
    public Result accessHistory(@RequestParam("shortUrl") String shortUrl,HttpServletRequest request){
        String userId = getUserId(request);
        return linkService.accessHistory(shortUrl,userId);
    }

    /**
     *   获取访问环境统计
     */
    @PostMapping("/accessEnvironment")
    public Result accessEnvironment(String timeType,HttpServletRequest request){
        String userId = getUserId(request);
        return linkService.accessEnvironment(timeType,userId);
    }

    /**
     *   获取访问操作系统统计
     */
    @PostMapping("/accessOS")
    public Result accessOS(String timeType,HttpServletRequest request){
        String userId = getUserId(request);
        return linkService.accessOS(timeType,userId);
    }

    /**
     *    获取地域分布
     */
    @PostMapping("/geographicalDistribution")
    public Result geographicalDistribution(@RequestBody StaticDTO staticDTO,HttpServletRequest request){
        String userId = getUserId(request);
        return linkService.geographicalDistribution(staticDTO,userId);
    }

    /**
     *   根据请求头获取用户ID
     */
    private String getUserId(HttpServletRequest request){
        return String.valueOf(AppJwtUtil.getJws(request.getHeader("token")).getBody().get("id"));
    }
}
